<template>
	   <NavBar></NavBar>
	<view class="data-analysis-page">
		<!-- 页面标题和操作按钮 -->
		<view class="page-header">
			<text class="title">数据分析</text>
			<button v-show="UserInfo.role.code == 1" class="edit-btn" @click="showCustomDataForm = true">编辑数据</button>
		</view>

		<!-- 数据概览卡片区域 -->
		<view class="data-cards-container">
			<view class="data-card" v-for="card in dataCards" :key="card.key" :style="{ borderLeft: `6rpx solid ${card.color || '#3C9CFF'}` }">
				<view class="card-header">
					<text class="card-title">{{ card.title }}</text>
				</view>
				<view class="card-content">
					<text class="card-value" :style="{ color: card.color || '#303133' }">{{ card.value }}</text>
				</view>
			</view>
		</view>

		<!-- 数据分析区域 -->
		<view class="analysis-container">
			<view class="analysis-title">
				<text>订单趋势分析</text>
			</view>
			<view class="analysis-content">
				<view class="analysis-item">
					<text class="item-label">统计周期:</text>
					<text class="item-value">{{ analysis.period }}</text>
				</view>
				<view class="analysis-item">
					<text class="item-label">总订单量:</text>
					<text class="item-value">{{ analysis.totalOrders }}</text>
				</view>
				<view class="analysis-item">
					<text class="item-label">平均每日订单:</text>
					<text class="item-value">{{ analysis.avgDailyOrders.toFixed(2) }}</text>
				</view>
				<view class="analysis-item">
					<text class="item-label">最高订单日:</text>
					<text class="item-value">{{ analysis.topDay.date }} ({{ analysis.topDay.orders }}单)</text>
				</view>
				<view class="analysis-item">
					<text class="item-label">订单增长率:</text>
					<text class="item-value">{{ analysis.growthRate.toFixed(2) }}%</text>
				</view>
				<view class="analysis-item">
					<text class="item-label">完成率:</text>
					<text class="item-value">{{ analysis.completionRate.toFixed(2) }}%</text>
				</view>
			</view>
		</view>

		<!-- 更新时间 -->
		<view class="update-info">
			<text class="info-text">数据更新时间: {{ updateTime }}</text>
		</view>

		<!-- 加载提示 -->
		<u-loading-popup v-model="loading.show" mode="flower" :text="loading.text"></u-loading-popup>
		
		<!-- 自定义数据编辑弹窗 -->
		<u-popup v-model="showCustomDataForm" mode="bottom" :closeable="true" @close="handleClosePopup">
			<view class="custom-data-form">
				<view class="form-header">
					<text class="form-title">自定义数据分析数据</text>
				</view>
				
				<view class="form-content">
					<!-- 基本数据输入 -->
					<view class="form-section">
						<text class="section-title">基本数据</text>
						
						<view class="form-item">
							<text class="item-label">总订单量</text>
							<input class="item-input" type="number" v-model.number="customData.total_orders" placeholder="请输入总订单量" />
						</view>
						
						<view class="form-item">
							<text class="item-label">完成订单</text>
							<input class="item-input" type="number" v-model.number="customData.completed_orders" placeholder="请输入完成订单数" />
						</view>
						
						<view class="form-item">
							<text class="item-label">取消订单</text>
							<input class="item-input" type="number" v-model.number="customData.cancelled_orders" placeholder="请输入取消订单数" />
						</view>
					</view>
					
					<!-- 收益数据输入 -->
					<view class="form-section">
						<text class="section-title">收益数据</text>
						
						<view class="form-item">
							<text class="item-label">总利润</text>
							<input class="item-input" type="number" step="0.01" v-model.number="customData.total_profit" placeholder="请输入总利润" />
						</view>
						
						<view class="form-item">
							<text class="item-label">今日利润</text>
							<input class="item-input" type="number" step="0.01" v-model.number="customData.today_profit" placeholder="请输入今日利润" />
						</view>
						
						<view class="form-item">
							<text class="item-label">本周利润</text>
							<input class="item-input" type="number" step="0.01" v-model.number="customData.week_profit" placeholder="请输入本周利润" />
						</view>
						
						<view class="form-item">
							<text class="item-label">本月利润</text>
							<input class="item-input" type="number" step="0.01" v-model.number="customData.month_profit" placeholder="请输入本月利润" />
						</view>
					</view>
					
					<!-- 时间范围设置 -->
					<view class="form-section">
						<text class="section-title">时间范围</text>
						
						<view class="form-item">
							<text class="item-label">开始日期</text>
							<input class="item-input" type="date" v-model="customData.start_date" />
						</view>
						
						<view class="form-item">
							<text class="item-label">结束日期</text>
							<input class="item-input" type="date" v-model="customData.end_date" />
						</view>
					</view>
				</view>
				
				<view class="form-actions">
					<button class="reset-btn" @click="resetCustomData">重置</button>
					<button class="save-btn" @click="saveCustomData">保存</button>
				</view>
			</view>
		</u-popup>
	<TabBar slot="bottom"></TabBar>
	</view>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { onLoad,  onShow } from '@dcloudio/uni-app'
import { readLocalStorage } from '@/static/js/hub'

// import { getOrderStatistics } from '@/static/apis/wzry.js'
const UserInfo = ref(readLocalStorage('userInfo'))

// 页面状态
const loading = reactive({
	show: false,
	text: '加载数据中...'
})

// 核心数据指标
const statisticsData = ref({})

// 数据卡片配置
const dataCards = ref([])

// 数据分析结果
const analysis = ref({
	period: '',
	totalOrders: 0,
	avgDailyOrders: 0,
	topDay: { date: '', orders: 0 },
	growthRate: 0,
	completionRate: 0
})

// 更新时间
const updateTime = ref('')

// 自定义数据表单显示状态
const showCustomDataForm = ref(false)

// 自定义数据结构
const customData = reactive({
	total_orders: 0,
	completed_orders: 0,
	cancelled_orders: 0,
	total_profit: 0,
	today_profit: 0,
	week_profit: 0,
	month_profit: 0,
	start_date: '',
	end_date: ''
})

// 获取订单统计数据 - 已注释掉API请求
/*
async function getOrderStats() {
	try {
		loading.show = true
		const res = await getOrderStatistics()
		if (res.code === 0 && res.data) {
			statisticsData.value = res.data
			// 处理图表数据
			handleChartData(res.data)
			// 处理数据卡片
			handleDataCards(res.data)
			// 更新时间
			updateTime.value = res.data.update_time || new Date().toLocaleString()
			uni.showToast({
				title: '数据加载成功',
				icon: 'success',
				duration: 1500
			})
		} else {
			uni.showToast({
				title: '数据加载失败',
				icon: 'error',
				duration: 2000
			})
		}
	} catch (error) {
		uni.showToast({
			title: '请求失败，请稍后重试',
			icon: 'error',
			duration: 2000
		})
		console.error('获取订单统计数据失败:', error)
	} finally {
		loading.show = false
	}
}
*/

// 处理图表数据并进行统计分析
function handleChartData(data) {
	// 优先使用自定义数据中的时间范围
	const startDate = data.start_date || ''
	const endDate = data.end_date || ''
	
	if (!data.trend_data) {
		// 如果没有趋势数据，使用默认的分析数据
		analysis.value = {
			period: `${startDate} 至 ${endDate}`,
			totalOrders: data.total_orders || 0,
			avgDailyOrders: 0,
			topDay: { date: '', orders: 0 },
			growthRate: 0,
			completionRate: data.total_orders > 0 ? (data.completed_orders / data.total_orders) * 100 : 0
		}
		return
	}

	// 使用趋势数据进行统计分析
	const trendData = data.trend_data

	// 计算统计分析
	const totalOrders = trendData.reduce((sum, item) => sum + (item.orders || 0), 0)
	const totalCompleted = trendData.reduce((sum, item) => sum + (item.completed || 0), 0)
	const avgDailyOrders = trendData.length > 0 ? totalOrders / trendData.length : 0
	const topDay = trendData.reduce((max, item) => {
		if ((item.orders || 0) > (max.orders || 0)) {
			return item
		}
		return max
	}, { date: '', orders: 0 })

	// 计算增长率（与第一个日期比较）
	let growthRate = 0
	if (trendData.length >= 2) {
		const firstOrders = trendData[0].orders || 0
		const lastOrders = trendData[trendData.length - 1].orders || 0
		if (firstOrders !== 0) {
			growthRate = ((lastOrders - firstOrders) / firstOrders) * 100
		}
	}

	// 计算完成率
	const completionRate = totalOrders !== 0 ? (totalCompleted / totalOrders) * 100 : 0

	// 更新分析数据，使用自定义的时间范围
	analysis.value = {
		period: `${startDate} 至 ${endDate}`,
		totalOrders: data.total_orders || totalOrders, // 优先使用直接提供的总订单量
		avgDailyOrders,
		topDay: { date: topDay.date, orders: topDay.orders || 0 },
		growthRate,
		completionRate
	}
}

// 处理数据卡片
function handleDataCards(data) {
	// 核心数据指标卡片
	const cards = [
		{ key: 'total_orders', title: '总订单量', value: data.total_orders || 0, color: '#3C9CFF' },
		{ key: 'completed_orders', title: '完成订单', value: data.completed_orders || 0, color: '#67C23A' },
		{ key: 'cancelled_orders', title: '取消订单', value: data.cancelled_orders || 0, color: '#F56C6C' },
		{ key: 'total_profit', title: '总利润', value: `¥${(data.total_profit || 0).toFixed(2)}`, color: '#E6A23C' },
		{ key: 'today_profit', title: '今日利润', value: `¥${(data.today_profit || 0).toFixed(2)}`, color: '#909399' },
		{ key: 'week_profit', title: '本周利润', value: `¥${(data.week_profit || 0).toFixed(2)}`, color: '#7265E6' },
		{ key: 'month_profit', title: '本月利润', value: `¥${(data.month_profit || 0).toFixed(2)}`, color: '#67C23A' }
	]
	
	// 添加动态样式，根据卡片值设置颜色
	cards.forEach(card => {
		// 为利润相关卡片添加特殊处理
		if (card.key.includes('profit')) {
			const profitValue = parseFloat(card.value.replace('¥', ''))
			if (profitValue > 0) {
				card.color = '#67C23A' // 正数利润显示绿色
			} else if (profitValue < 0) {
				card.color = '#F56C6C' // 负数利润显示红色
			}
		}
	})
	
	dataCards.value = cards
}

// 生成趋势数据（根据日期范围生成模拟的趋势数据）
function generateTrendData(startDate, endDate) {
	const start = new Date(startDate)
	const end = new Date(endDate)
	const trendData = []
	const current = new Date(start)
	
	while (current <= end) {
		const dateStr = current.toISOString().split('T')[0]
		// 生成随机订单数据，确保有一定的波动性
		const baseOrders = Math.floor(Math.random() * 30) + 50
		const orders = baseOrders + Math.floor(Math.random() * 20) - 10
		const completed = Math.floor(orders * (0.8 + Math.random() * 0.15))
		const cancelled = orders - completed
		
		trendData.push({
			date: dateStr,
			orders,
			completed,
			cancelled
		})
		
		// 下一天
		current.setDate(current.getDate() + 1)
	}
	
	return trendData
}

// 加载默认数据
function loadDefaultData() {
	// 设置默认数据：时间范围从2025-10-01到2025-11-23，期间收益为4千多元
	const defaultData = {
		total_orders: 1250,
		completed_orders: 1050,
		cancelled_orders: 200,
		total_profit: 4250.80,
		today_profit: 158.50,
		week_profit: 1056.20,
		month_profit: 3850.75,
		start_date: '2025-10-01',
		end_date: '2025-11-23'
	}
	
	// 更新自定义数据
	objectAssign(customData, defaultData)
	
	// 生成趋势数据
	const trendData = generateTrendData(defaultData.start_date, defaultData.end_date)
	
	// 构建完整的数据对象
	const fullData = {
		...defaultData,
		trend_data: trendData,
		update_time: new Date().toLocaleString()
	}
	
	// 处理数据
	statisticsData.value = fullData
	handleChartData(fullData)
	handleDataCards(fullData)
	updateTime.value = fullData.update_time
	
	// 保存到本地存储
	saveToStorage(fullData)
}

// 从本地存储加载数据
function loadStoredData() {
	try {
		const stored = uni.getStorageSync('custom_analysis_data')
		if (stored) {
			const data = JSON.parse(stored)
			// 更新自定义数据
			objectAssign(customData, {
				total_orders: data.total_orders || 0,
				completed_orders: data.completed_orders || 0,
				cancelled_orders: data.cancelled_orders || 0,
				total_profit: data.total_profit || 0,
				today_profit: data.today_profit || 0,
				week_profit: data.week_profit || 0,
				month_profit: data.month_profit || 0,
				start_date: data.start_date || '',
				end_date: data.end_date || ''
			})
			
			// 处理数据
			statisticsData.value = data
			handleChartData(data)
			handleDataCards(data)
			updateTime.value = data.update_time
		} else {
			// 没有存储的数据，加载默认数据
			loadDefaultData()
		}
	} catch (error) {
		console.error('加载存储数据失败:', error)
		// 加载默认数据
		loadDefaultData()
	}
}

// 保存数据到本地存储
function saveToStorage(data) {
	try {
		uni.setStorageSync('custom_analysis_data', JSON.stringify(data))
	} catch (error) {
		console.error('保存数据失败:', error)
	}
}

// 保存自定义数据
function saveCustomData() {
	// 验证日期范围
	if (!customData.start_date || !customData.end_date) {
		uni.showToast({
			title: '请设置完整的时间范围',
			icon: 'error',
			duration: 2000
		})
		return
	}
	
	if (new Date(customData.start_date) > new Date(customData.end_date)) {
		uni.showToast({
			title: '开始日期不能晚于结束日期',
			icon: 'error',
			duration: 2000
		})
		return
	}
	
	// 生成趋势数据
	const trendData = generateTrendData(customData.start_date, customData.end_date)
	
	// 构建完整的数据对象
	const fullData = {
		...customData,
		trend_data: trendData,
		update_time: new Date().toLocaleString()
	}
	
	// 处理数据
	statisticsData.value = fullData
	handleChartData(fullData)
	handleDataCards(fullData)
	updateTime.value = fullData.update_time
	
	// 保存到本地存储
	saveToStorage(fullData)
	
	// 关闭弹窗
	showCustomDataForm.value = false
	
	// 显示成功提示
	uni.showToast({
		title: '数据保存成功',
		icon: 'success',
		duration: 1500
	})
}

// 重置自定义数据
function resetCustomData() {
	// 重置为默认值
	const defaultData = {
		total_orders: 1250,
		completed_orders: 1050,
		cancelled_orders: 200,
		total_profit: 4250.80,
		today_profit: 158.50,
		week_profit: 1056.20,
		month_profit: 3850.75,
		start_date: '2025-10-01',
		end_date: '2025-11-23'
	}
	
	objectAssign(customData, defaultData)
}

// 处理弹窗关闭
function handleClosePopup() {
	// 这里可以添加清理逻辑
	showCustomDataForm.value = false
}

// 辅助函数：对象属性赋值
function objectAssign(target, source) {
	for (const key in source) {
		if (source.hasOwnProperty(key)) {
			target[key] = source[key]
		}
	}
}

// 页面加载时获取数据 - 将使用自定义数据而非API请求
onMounted(() => {
	// getOrderStats()
	loadDefaultData()
})

// 页面显示时刷新数据
onShow(() => {
	// getOrderStats()
	// 从存储中加载数据
	loadStoredData()
})
</script>

<style scoped lang="scss">
.data-analysis-page {
	min-height: 100vh;
	background-color: #f5f7fa;
	padding: 20rpx;
}

.page-header {
	padding: 20rpx 0;
	margin-bottom: 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;

	.title {
		font-size: 36rpx;
		font-weight: 600;
		color: #303133;
	}
	
	.edit-btn {
		padding: 12rpx 32rpx;
		font-size: 24rpx;
		background-color: #3C9CFF;
		color: white;
		border-radius: 20rpx;
		border: none;
	}
}

.data-cards-container {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
	gap: 20rpx;
	margin-bottom: 40rpx;
}

.data-card {
	width: calc(50% - 10rpx);
	background-color: #ffffff;
	border-radius: 16rpx;
	padding: 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	transition: all 0.3s ease;

	&:hover {
		transform: translateY(-4rpx);
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	}
}

.card-header {
	margin-bottom: 16rpx;
}

.card-title {
	font-size: 24rpx;
	color: #909399;
}

.card-content {
	.card-value {
		font-size: 36rpx;
		font-weight: 600;
		color: #303133;
	}
}

.analysis-container {
	background-color: #ffffff;
	border-radius: 16rpx;
	padding: 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	margin-bottom: 20rpx;
}

.analysis-title {
	margin-bottom: 24rpx;
	text {
		font-size: 30rpx;
		font-weight: 600;
		color: #303133;
	}
}

.analysis-content {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.analysis-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12rpx 0;
	border-bottom: 1rpx solid #f5f7fa;

	&:last-child {
		border-bottom: none;
	}
}

.item-label {
	font-size: 24rpx;
	color: #909399;
}

.item-value {
	font-size: 26rpx;
	font-weight: 600;
	color: #303133;
}

.update-info {
	padding: 16rpx;
	text-align: center;

	.info-text {
		font-size: 22rpx;
		color: #909399;
	}
}

/* 自定义数据表单样式 */
.custom-data-form {
	padding: 30rpx;
}

.form-header {
	text-align: center;
	margin-bottom: 30rpx;
	
	.form-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #303133;
	}
}

.form-content {
	max-height: 60vh;
	overflow-y: auto;
}

.form-section {
	margin-bottom: 30rpx;
	
	.section-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #303133;
		margin-bottom: 20rpx;
		display: block;
	}
}

.form-item {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
	
	.item-label {
		width: 180rpx;
		font-size: 26rpx;
		color: #606266;
	}
	
	.item-input {
		flex: 1;
		height: 70rpx;
		padding: 0 20rpx;
		border: 1rpx solid #dcdfe6;
		border-radius: 8rpx;
		font-size: 26rpx;
		color: #303133;
	}
}

.form-actions {
	display: flex;
	gap: 20rpx;
	margin-top: 30rpx;
	
	.reset-btn,
	.save-btn {
		flex: 1;
		height: 80rpx;
		font-size: 28rpx;
		border-radius: 10rpx;
		border: none;
	}
	
	.reset-btn {
		background-color: #f5f7fa;
		color: #606266;
	}
	
	.save-btn {
		background-color: #3C9CFF;
		color: white;
	}
}
</style>
